﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WFNetLib;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using WFNetLib.GSMModem;
using WFNetLib.Forms;
using WFNetLib.Net;
using System.IO;
using System.IO.Compression;
using System.Net;

namespace ATReaderTest
{
    public class ReaderThread
    {
        public SerialPort Com;
        public Thread ReaderThreadIns=null;
        public static event strEventHandler AddLogEvent;//事件声明
#if DEBUG
        CommunicationDebugForm CommunicationDebugForm;
#endif


        GsmModem gsmModem;
        public string PortName;
        void OnAddLog(string strLog)
        {
            if (AddLogEvent != null)
            {                
                AddLogEvent(this,new strEventArgs(strLog));
            }
        }        
        public ReaderThread(SerialPort _Com)
        {
            Com = _Com;
            
#if DEBUG
            CommunicationDebugForm = new CommunicationDebugForm();
            CommunicationDebugForm.Show();
            //CommunicationDebugForm.Hide();
            CommunicationDebugForm.Text = Com.PortName + "数据检测";
            gsmModem = new GsmModem(Com);//gsmModem = new GsmModem(Com,CommunicationDebugForm);
#else
            gsmModem = new GsmModem(Com);
#endif
           

            gsmModem.dIP[0] = 10;
            gsmModem.dIP[1] = 0;
            gsmModem.dIP[2] = 0;
            gsmModem.dIP[3] = 172;
            gsmModem.dPort = 80;
            
//             gsmModem.sIP = new byte[4];
//             gsmModem.sIP[0] = 10;
//             gsmModem.sIP[1] = 0xbd;
//             gsmModem.sIP[2] = 0xf0;
//             gsmModem.sIP[3] = 0xce;
            gsmModem.AddLog += new strEventHandler(gsmModem_AddLog);
            
        }

        void gsmModem_AddLog(object sender, strEventArgs e)
        {
            OnAddLog(e.strArg);
        }
        public void ReaderThreadStart()
        {
            ReaderThreadIns = new Thread(new ThreadStart(ReaderProc));
            ReaderThreadIns.Name = "签到" + Com.PortName;
            PortName = Com.PortName;
            ReaderThreadIns.Start();
            OnAddLog("签到开始");
        }
        private void ReaderProc()
        {
            while(true)
            {
                try
                {
                    Com.Open();                    
                    //Com.RtsEnable = true;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    OnAddLog("串口" + Com.PortName + "无法打开");
                    break;
                }
                if (!gsmModem.InitGSMModem())
                {
                    OnAddLog(ReaderThreadIns.Name + "初始化失败");
                    break;
                }                
                OnAddLog(ReaderThreadIns.Name + "初始化成功");
                if (gsmModem.strATI == "HUAWEIGTM900")
                {

                    if (!gsmModem.GTM900_InitTCPIP())
                    {
                        OnAddLog("<模块需要重新上电>");
                        break;
                    }
                    string uri = "http://go.10086.cn/g/signInUser.do?fpid=408035&signInId=371&pid=408030&themeid=18284&ptype=22&num=&integralType=0&integralTime=0";
                    WebHeaderCollection httpHeader = new WebHeaderCollection();
                    httpHeader[HttpRequestHeader.UserAgent] = "NokiaN82/1.0 (20.1.062) SymbianOS/9.2 Series60/3.1 Profile/MIDP-2.0 Configuration/CLDC-1.1";
                    httpHeader[HttpRequestHeader.Accept] = "*/*";
                    httpHeader[HttpRequestHeader.AcceptEncoding] = "*/*";
                    httpHeader[HttpRequestHeader.AcceptLanguage] = "zh-CN, en-US";
                    CookieCollection cookies = new CookieCollection();
                    string tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
#if DEBUG
                    CommunicationDebugForm.ExternShowTx(tx);
#endif
                    //                     StringBuilder sb = new StringBuilder();
                    //                     sb.Append("GET http://go.10086.cn/ HTTP/1.1" + "\r\n");
                    //                     sb.Append("User-Agent: NokiaN82/1.0 (20.1.062) SymbianOS/9.2 Series60/3.1 Profile/MIDP-2.0 Configuration/CLDC-1.1" + "\r\n");
                    //                     sb.Append("Host: go.10086.cn" + "\r\n");
                    //                     sb.Append("Accept: application/vnd.wap.xhtml+xml,application/xml,text/vnd.wap.wml,text/html,application/xhtml+xml,image/jpeg;q=0.5,image/png;q=0.5,image/gif;q=0.5,image/*;q=0.6,video/*,audio/*,*/*;q=0.6,UC/139" + "\r\n");
                    //                     sb.Append("Accept-Encoding: gzip" + "\r\n");
                    //                     sb.Append("Accept-Language: zh-CN, en-US" + "\r\n");
                    //                     sb.Append("Connection: Keep-Alive" + "\r\n");
                    //                     //sb.Append("Cookie: jid=YknbTs2Xqv!139046290; path=/" + "\r\n");
                    //                     sb.Append("\r\n");
                    object o = gsmModem.GTM900_TCPIPRead(tx);
                    if (o == null)
                        break;
                    Http http = (Http)o;
                    string str = "";
                    if (http.ContentDatas.Count == 0)
                        break;
                    str = HttpStatic.ContentToStr(http);
#if DEBUG
                    CommunicationDebugForm.ExternShowRx(str);
#endif
                    int x = str.IndexOf("onevent type=\"onenterforward\"");
                    if (x != -1)
                    {
                        x = str.IndexOf("go href=\"", x);
                        if (x != -1)
                        {
                            x += 9;
                            OnAddLog("获得跳转页");
                            httpHeader[HttpRequestHeader.Referer] = uri;
                            uri = WFNetLib.Strings.StringsFunction.strDecode(str.Substring(x, str.IndexOf('\"', x) - x));
                            if (http.Cookies.Count != 0)
                            {
                                foreach (Cookie c in http.Cookies)
                                {
                                    if (cookies[c.Name] != null)
                                        cookies[c.Name].Value = c.Value;
                                    else
                                        cookies.Add(c);
                                }
                            }
                            tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
#if DEBUG
                            CommunicationDebugForm.ExternShowTx(tx);
#endif
                            o = gsmModem.GTM900_TCPIPRead(tx);
                        }
                    }
                    if (o == null)
                        break;
                    http = (Http)o;
                    OnAddLog("获得签到页");
                    str = HttpStatic.ContentToStr(http);//signCode=2984&signCodeSystem=298&themeid=18284&signInId=371&ptype=22&fpid=408035&pid=408030
#if DEBUG
                    CommunicationDebugForm.ExternShowRx(str);
#endif
                    string signCode;
                    string signCodeSystem;
                    string themeid;
                    string signInId;
                    string ptype;
                    string fpid;
                    string pid;
                    x = str.IndexOf("confirmCode?code=");
                    if (x == -1)
                        break;
                    x += "confirmCode?code=".Length;
                    signCode = str.Substring(x, str.IndexOf('\"', x) - x);
                    x = str.IndexOf("name=\"signCodeSystem\" value=\"");
                    if (x == -1)
                        break;
                    x += "name=\"signCodeSystem\" value=\"".Length;
                    signCodeSystem = str.Substring(x, str.IndexOf('\"', x) - x);

                    //                     if (signCode != signCodeSystem)
                    //                     {
                    //                         if (signCodeSystem.Length == 4 && signCode.Length < 4)
                    //                         {
                    //                             signCode = signCodeSystem;
                    //                         }
                    //                     }

                    x = str.IndexOf("name=\"themeid\" value=\"");
                    if (x == -1)
                        break;
                    x += "name=\"themeid\" value=\"".Length;
                    themeid = str.Substring(x, str.IndexOf('\"', x) - x);

                    x = str.IndexOf("name=\"signInId\" value=\"");
                    if (x == -1)
                        break;
                    x += "name=\"signInId\" value=\"".Length;
                    signInId = str.Substring(x, str.IndexOf('\"', x) - x);

                    x = str.IndexOf("name=\"ptype\" value=\"");
                    if (x == -1)
                        break;
                    x += "name=\"ptype\" value=\"".Length;
                    ptype = str.Substring(x, str.IndexOf('\"', x) - x);

                    x = str.IndexOf("name=\"fpid\" value=\"");
                    if (x == -1)
                        break;
                    x += "name=\"fpid\" value=\"".Length;
                    fpid = str.Substring(x, str.IndexOf('\"', x) - x);

                    x = str.IndexOf("name=\"pid\" value=\"");
                    if (x == -1)
                        break;
                    x += "name=\"pid\" value=\"".Length;
                    pid = str.Substring(x, str.IndexOf('\"', x) - x);

                    x = str.IndexOf("confirmCode?code=");
                    if (x == -1)
                        break;
                    uri = str.Substring(x, str.IndexOf('\"', x) - x);
                    if (uri.IndexOf("http://") == -1)
                    {
                        uri = "http://go.10086.cn/g/" + uri;
                        //                         x = httpHeader[HttpRequestHeader.Referer].IndexOf("do?");
                        //                         x = httpHeader[HttpRequestHeader.Referer].LastIndexOf("/", x);
                        //                         uri = httpHeader[HttpRequestHeader.Referer].Substring(0, x + 1) + uri;
                    }
                    if (http.Cookies != null && http.Cookies.Count != 0)
                    {
                        foreach (Cookie c in http.Cookies)
                        {
                            if (cookies[c.Name] != null)
                                cookies[c.Name].Value = c.Value;
                            else
                                cookies.Add(c);
                        }
                    }
                    tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
                    o = gsmModem.GTM900_TCPIPRead(tx);
#if DEBUG
                    CommunicationDebugForm.ExternShowTx(tx);
#endif
                    if (o == null)
                        break;
                    http = (Http)o;
                    OnAddLog("获得验证码图片");
                    if (http.ContentDatas.Count != 0)
                    {
                        if (http.httpHeader[HttpResponseHeader.ContentType].IndexOf("image") != -1)
                        {
                            string ext = http.httpHeader[HttpResponseHeader.ContentType].Split('/')[1];
                            string file = System.Windows.Forms.Application.StartupPath + "\\gif\\" + ReaderThreadIns.Name + DateTime.Now.ToString("yyyyMMdd_hhmmss") + "." + ext;
                            FileInfo f = new FileInfo(file);
                            if (!Directory.Exists(f.DirectoryName))
                                Directory.CreateDirectory(f.DirectoryName);
                            FileStream fs = new FileStream(file, FileMode.Create);
                            BinaryWriter bw = new BinaryWriter(fs);
                            bw.Write(http.ContentDatas.ToArray());
                            //清空缓冲区
                            bw.Flush();
                            //关闭流
                            bw.Close();
                            fs.Close();/**/

                        }
                    }
                    uri = "http://go.10086.cn/g/signInCode.do";
                    if (http.Cookies.Count != 0)
                    {
                        foreach (Cookie c in http.Cookies)
                        {
                            if (cookies[c.Name] != null)
                                cookies[c.Name].Value = c.Value;
                            else
                                cookies.Add(c);
                        }
                    }
                    //signCode=2984&signCodeSystem=298&themeid=18284&signInId=371&ptype=22&fpid=408035&pid=408030                    
                    string post = "signCode=" + signCode + "&";
                    post = post + "signCodeSystem=" + signCodeSystem + "&";
                    post = post + "themeid=" + themeid + "&";
                    post = post + "signInId=" + signInId + "&";
                    post = post + "ptype=" + ptype + "&";
                    post = post + "fpid=" + fpid + "&";
                    post = post + "pid=" + pid;
                    Debug.WriteLine(post);
                    httpHeader[HttpRequestHeader.ContentLength] = post.Length.ToString();
                    httpHeader[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    tx = HttpStatic.HttpHeaderToStr("POST", uri, httpHeader, cookies);
#if DEBUG
                    CommunicationDebugForm.ExternShowTx(tx);
#endif
                    tx = tx + post;
                    Debug.WriteLine(tx);
                    OnAddLog("进行签到");
                    o = gsmModem.GTM900_TCPIPRead(tx);

                    if (o == null)
                        break;
                    http = (Http)o;
                    str = HttpStatic.ContentToStr(http);
#if DEBUG
                    CommunicationDebugForm.ExternShowRx(str);
#endif
                    gsmModem.GTM900_CloseTCPIP();
                    if (str.IndexOf("签到成功") != -1)
                    {
                        //OnAddLog("签到成功");
                        OnAddLog("<签到已经成功>");
                        Com.Close();
                        return;
                    }
                    else if (str.IndexOf("签到失败（一天只允许签到一次）") != -1)
                    {
                        //OnAddLog("签到失败（一天只允许签到一次）");
                        OnAddLog("<签到失败（一天只允许签到一次）>");
                        Com.Close();
                        return;
                    }
                    else
                    {
                        //OnAddLog("未知签到结果");
                        OnAddLog("<未知签到结果,重新签到>");
                        Com.Close();
                        return;
                    }                    
                }
//                 if (!gsmModem.InitGSMModem())
//                 {
//                     OnAddLog(ReaderThreadIns.Name + "初始化失败");
//                     break;
//                 }
//                 OnAddLog(ReaderThreadIns.Name + "初始化成功");
//                 if (!gsmModem.InitPPPConnect())
//                 {
//                     OnAddLog("拨号失败");
//                     break;
//                 }
//                 OnAddLog("拨号成功");
//                 string uri = "http://go.10086.cn/g/signInUser.do?fpid=408035&signInId=371&pid=408030&themeid=18284&ptype=22&num=&integralType=0&integralTime=0";
//                 WebHeaderCollection httpHeader = new WebHeaderCollection();
//                 httpHeader[HttpRequestHeader.UserAgent] = "NokiaN82/1.0 (20.1.062) SymbianOS/9.2 Series60/3.1 Profile/MIDP-2.0 Configuration/CLDC-1.1";
//                 httpHeader[HttpRequestHeader.Accept] = "*/*";
//                 httpHeader[HttpRequestHeader.AcceptEncoding] = "*/*";
//                 httpHeader[HttpRequestHeader.AcceptLanguage] = "zh-CN, en-US";
//                 CookieCollection cookies = new CookieCollection();
//                 string tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
//                 if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
//                 {
//                     OnAddLog("获得tcp数据失败!");
//                     break;
//                 }
//                 object o;
//                 o = gsmModem.TCPData.oTCPDatas;
//                 if (o == null)
//                     break;
//                 Http http = (Http)o;
//                 string str = "";
//                 if (http.ContentDatas.Count == 0)
//                     break;
//                 str = HttpStatic.ContentToStr(http);
//                 int x = str.IndexOf("onevent type=\"onenterforward\"");
//                 if (x != -1)
//                 {
//                     x = str.IndexOf("go href=\"", x);
//                     if (x != -1)
//                     {
//                         x += 9;
//                         OnAddLog("获得跳转页");
//                         httpHeader[HttpRequestHeader.Referer] = uri;
//                         uri = WFNetLib.Strings.StringsFunction.strDecode(str.Substring(x, str.IndexOf('\"', x) - x));
//                         if (http.Cookies.Count != 0)
//                         {
//                             foreach (Cookie c in http.Cookies)
//                             {
//                                 if (cookies[c.Name] != null)
//                                     cookies[c.Name].Value = c.Value;
//                                 else
//                                     cookies.Add(c);
//                             }
//                         }
//                         tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
//                         if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
//                         {
//                             OnAddLog("获得tcp数据失败!");
//                             break;
//                         }
//                     }
//                 }
//                 o = gsmModem.TCPData.oTCPDatas;
//                 if (o == null)
//                     break;
//                 http = (Http)o;
//                 OnAddLog("获得签到页");
//                 str = HttpStatic.ContentToStr(http);//signCode=2984&signCodeSystem=298&themeid=18284&signInId=371&ptype=22&fpid=408035&pid=408030
//                 string signCode;
//                 string signCodeSystem;
//                 string themeid;
//                 string signInId;
//                 string ptype;
//                 string fpid;
//                 string pid;
//                 x = str.IndexOf("confirmCode?code=");
//                 if (x == -1)
//                     break;
//                 x += "confirmCode?code=".Length;
//                 signCode = str.Substring(x, str.IndexOf('\"', x) - x);
//                 x = str.IndexOf("name=\"signCodeSystem\" value=\"");
//                 if (x == -1)
//                     break;
//                 x += "name=\"signCodeSystem\" value=\"".Length;
//                 signCodeSystem = str.Substring(x, str.IndexOf('\"', x) - x);
// 
//                 //                     if (signCode != signCodeSystem)
//                 //                     {
//                 //                         if (signCodeSystem.Length == 4 && signCode.Length < 4)
//                 //                         {
//                 //                             signCode = signCodeSystem;
//                 //                         }
//                 //                     }
// 
//                 x = str.IndexOf("name=\"themeid\" value=\"");
//                 if (x == -1)
//                     break;
//                 x += "name=\"themeid\" value=\"".Length;
//                 themeid = str.Substring(x, str.IndexOf('\"', x) - x);
// 
//                 x = str.IndexOf("name=\"signInId\" value=\"");
//                 if (x == -1)
//                     break;
//                 x += "name=\"signInId\" value=\"".Length;
//                 signInId = str.Substring(x, str.IndexOf('\"', x) - x);
// 
//                 x = str.IndexOf("name=\"ptype\" value=\"");
//                 if (x == -1)
//                     break;
//                 x += "name=\"ptype\" value=\"".Length;
//                 ptype = str.Substring(x, str.IndexOf('\"', x) - x);
// 
//                 x = str.IndexOf("name=\"fpid\" value=\"");
//                 if (x == -1)
//                     break;
//                 x += "name=\"fpid\" value=\"".Length;
//                 fpid = str.Substring(x, str.IndexOf('\"', x) - x);
// 
//                 x = str.IndexOf("name=\"pid\" value=\"");
//                 if (x == -1)
//                     break;
//                 x += "name=\"pid\" value=\"".Length;
//                 pid = str.Substring(x, str.IndexOf('\"', x) - x);
// 
//                 x = str.IndexOf("confirmCode?code=");
//                 if (x == -1)
//                     break;
//                 uri = str.Substring(x, str.IndexOf('\"', x) - x);
//                 if (uri.IndexOf("http://") == -1)
//                 {
//                     uri = "http://go.10086.cn/g/" + uri;
//                     //                         x = httpHeader[HttpRequestHeader.Referer].IndexOf("do?");
//                     //                         x = httpHeader[HttpRequestHeader.Referer].LastIndexOf("/", x);
//                     //                         uri = httpHeader[HttpRequestHeader.Referer].Substring(0, x + 1) + uri;
//                 }
//                 if (http.Cookies != null && http.Cookies.Count != 0)
//                 {
//                     foreach (Cookie c in http.Cookies)
//                     {
//                         if (cookies[c.Name] != null)
//                             cookies[c.Name].Value = c.Value;
//                         else
//                             cookies.Add(c);
//                     }
//                 }
//                 tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
//                 if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
//                 {
//                     OnAddLog("获得tcp数据失败!");
//                     break;
//                 }
//                 o = gsmModem.TCPData.oTCPDatas;
//                 if (o == null)
//                     break;
//                 http = (Http)o;
//                 OnAddLog("获得验证码图片");
//                 if (http.ContentDatas.Count != 0)
//                 {
//                     if (http.httpHeader[HttpResponseHeader.ContentType].IndexOf("image") != -1)
//                     {
//                         string ext = http.httpHeader[HttpResponseHeader.ContentType].Split('/')[1];
//                         string file = System.Windows.Forms.Application.StartupPath + "\\gif\\" + ReaderThreadIns.Name + DateTime.Now.ToString("yyyyMMdd_hhmmss") + "." + ext;
//                         FileInfo f = new FileInfo(file);
//                         if (!Directory.Exists(f.DirectoryName))
//                             Directory.CreateDirectory(f.DirectoryName);
//                         FileStream fs = new FileStream(file, FileMode.Create);
//                         BinaryWriter bw = new BinaryWriter(fs);
//                         bw.Write(http.ContentDatas.ToArray());
//                         //清空缓冲区
//                         bw.Flush();
//                         //关闭流
//                         bw.Close();
//                         fs.Close();/**/
// 
//                     }
//                 }
//                 uri = "http://go.10086.cn/g/signInCode.do";
//                 if (http.Cookies.Count != 0)
//                 {
//                     foreach (Cookie c in http.Cookies)
//                     {
//                         if (cookies[c.Name] != null)
//                             cookies[c.Name].Value = c.Value;
//                         else
//                             cookies.Add(c);
//                     }
//                 }
//                 //signCode=2984&signCodeSystem=298&themeid=18284&signInId=371&ptype=22&fpid=408035&pid=408030                    
//                 string post = "signCode=" + signCode + "&";
//                 post = post + "signCodeSystem=" + signCodeSystem + "&";
//                 post = post + "themeid=" + themeid + "&";
//                 post = post + "signInId=" + signInId + "&";
//                 post = post + "ptype=" + ptype + "&";
//                 post = post + "fpid=" + fpid + "&";
//                 post = post + "pid=" + pid;
//                 Debug.WriteLine(post);
//                 httpHeader[HttpRequestHeader.ContentLength] = post.Length.ToString();
//                 httpHeader[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
//                 tx = HttpStatic.HttpHeaderToStr("POST", uri, httpHeader, cookies);
//                 tx = tx + post;
//                 Debug.WriteLine(tx);
//                 OnAddLog("进行签到");
//                 if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
//                 {
//                     OnAddLog("获得tcp数据失败!");
//                     break;
//                 }
// 
//                 o = gsmModem.TCPData.oTCPDatas;
//                 if (o == null)
//                     break;
//                 http = (Http)o;
//                 str = HttpStatic.ContentToStr(http);
//                 if (str.IndexOf("签到成功") != -1)
//                     OnAddLog("签到成功");
//                 else if (str.IndexOf("签到失败（一天只允许签到一次）") != -1)
//                     OnAddLog("签到失败（一天只允许签到一次）");
//                 else
//                 {
//                     OnAddLog("未知签到结果");
//                 }
//                 if (!gsmModem.pppClose())
//                 {
//                     OnAddLog("ppp关闭失败");
//                 }
//                 else
//                 {
//                     OnAddLog("ppp关闭成功");
//                 }
                 break;
            }
            Debug.WriteLine("完成");
            OnAddLog("<未知退出>");
            Com.Close();
        }        
    }
}
